package org.tgcloud.group.core;

import com.alibaba.excel.write.handler.AbstractSheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;

public class AutoWidthHandler extends AbstractSheetWriteHandler {

    private final List<List<String>> headList;
    private final List<List<Object>> dataList;

    public AutoWidthHandler(List<List<String>> headList, List<List<Object>> dataList) {
        this.headList = headList;
        this.dataList = dataList;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder,
                                 WriteSheetHolder writeSheetHolder) {

        Sheet sheet = writeSheetHolder.getSheet();
        int columnCount = headList.size();

        for (int col = 0; col < columnCount; col++) {

            // 先按表头宽度计算
            int maxWidth = headList.get(col).get(0).getBytes().length;

            // 再按内容计算
            for (List<Object> row : dataList) {
                if (col < row.size() && row.get(col) != null) {
                    String v = row.get(col).toString();
                    int w = v.getBytes().length;
                    maxWidth = Math.max(maxWidth, w);
                }
            }

            // 设置列宽（256 是单位）
            sheet.setColumnWidth(col, Math.min((maxWidth + 2) * 256, 255 * 256));
        }
    }
}
